<template>
	<div class="card-header-box1">
		<el-form ref="queryForm" :inline="true" :model="formParams" :rules="rules">
			<el-form-item prop="baopCompletionTime" label="完成时间:">
				<el-date-picker
					v-model="formParams.baopCompletionTime"
					type="date"
					value-format="YYYY-MM-DD HH:mm:ss"
					format="YYYY-MM-DD"
					style="width: 100%"
					:disabled="!getedit"
				/>
			</el-form-item>

			<el-form-item label="阶段状态:" class="ml20">
				<div style="color: #666">
					{{
						props.datainfo.progressColor == 'green' || props.datainfo.progressColor == ''
							? '正常'
							: props.datainfo.progressColor == 'orange' || props.datainfo.progressColor == 'red'
								? '滞后'
								: ''
					}}
				</div>
			</el-form-item>

			<el-form-item label="标准详细信息填报:" class="ml20">
				<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="handleBiaozhun">
					<Tickets />
				</el-icon>
			</el-form-item>

			<el-form-item class="ml20">
				<el-button type="primary" @click="handleFileDownload">报批资料</el-button>
			</el-form-item>

			<!-- 2025.10.11 适用范围暂时不要了 -->
			<!-- <el-form-item label="适用范围:">
				<el-input v-model="formParams.scopeApplication" type="textarea" :disabled="!getedit" :rows="3" style="width: 600px" />
			</el-form-item> -->
		</el-form>

		<div class="titlezi flex">
			<div class="flex-1">主编单位</div>
		</div>

		<div class="kuaibj mt20">
			<Cfupload
				v-for="value in fjcodelist"
				:key="value"
				:istable="false"
				:labeltitle="value.definitionName"
				:code="value.businessCode"
				:suffix-type="value.suffixType"
				:filelist="value.uploadedFiles"
				:disabled="getedit"
				:ismust="value.imustUpload"
				@success="handleUploadSuccess"
				@remove="handleFileRemove"
			></Cfupload>
			<!-- <div class="titlezi flex flex-align-center">
					<div class="">标准详细信息</div>
					<div class="color1491FF font14 ml60 cursor" >详情</div>
				</div>  v-if="Number(props.requestParams.progressStatus) == 10"-->
		</div>

		<div class="dialog-footer mt10">
			<el-button v-if="zancunshow" type="success" @click="zanchSubmit">暂存</el-button>
			<el-button v-if="shangbaoshow" type="primary" @click="hanvisible = true">上报</el-button>
			<el-button v-if="zancunshow" type="primary" @click="endSubmit">提交</el-button>
			<el-button
				v-if="
					Number(props.requestParams.progressStatus) == 10 &&
					props.datainfo.edit == 'true' &&
					!userStore.user.roleCode.includes('SHZJW') &&
					!userStore.user.roleCode.includes('SB')
				"
				type="primary"
				plain
				@click="cancelSubmit"
				>退回</el-button
			>
		</div>

		<ShangbaoDialog v-model:visible="hanvisible" :standard-number="formParams.standardNumber" @changenumber="baoSubmit"></ShangbaoDialog>

		<biaozhunxinxichakan v-model="showbzxx" :edit-id="props.datainfo.id"></biaozhunxinxichakan>
		<biaozhunkuDialog v-model="showAddDialog" :edit-id="editId" :project-id="projectId" :is-disabled="!getedit" @submit-success="addSuccess" />
	</div>
</template>
<script setup lang="ts">
import { doReturnApi, queryFilesSettingApi, updateProgressApi, updateStageAndStatusApi, exportApprovalListApi } from '@/api/bianzhi/index'
import Cfupload from '@/components/cf-upload/index.vue'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, defineProps, nextTick, onMounted, reactive, ref, watch } from 'vue'
import ShangbaoDialog from '../components/shangbaoDialog.vue'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
// 标准信息查看
import biaozhunkuDialog from '@/views/Standard/maintenance/components/addDialog.vue'
import biaozhunxinxichakan from '@/views/Standard/maintenance/components/update.vue'
import { useRoute } from 'vue-router'

const userStore = useUserStore()
const emit = defineEmits<{ (event: 'updateData', value: ''): void }>()
const hanvisible = ref(false)

// 标准信息查询
const showbzxx = ref(false)
const bzsbId = ref('')

const dictionaryStore = useDictionaryStore()
const jdstatuslist = dictionaryStore.getDictionaryByCode('T007')
const fjcodelist = ref(null)
const fjcodelist1 = ref(null)
const datalist = ref([])
const uploadedFiles = ref([])
const queryForm = ref(null)
const formParams = ref({} as any)
const props = defineProps({
	datainfo: {
		type: Object,
		default: () => ({})
	},
	requestParams: {
		type: Object,
		default: () => ({})
	}
})
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const projectId = ref<string>('')

const addSuccess = (e: any) => {}

watch(
	() => showAddDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			projectId.value = ''
		}
	}
)

watch(
	() => props.requestParams,
	(newVal: any, oldVal: any) => {
		//console.log(props.requestParams.standardNumber, '我是props的datainfo')
		formParams.value = props.requestParams || {} //给form赋值
		queryFilesSettingApi({ businessStage: 'ApprovalApplication' }).then(res => {
			fjcodelist.value = res.data
			nextTick(() => {
				///  console.log(props.requestParams.solicitOpinionsBeforeFileList.length, '我是大纲附件们' )
				if (props.requestParams.approvalApplicationFileList.length > 0) {
					const aa: any = props.requestParams.approvalApplicationFileList
					uploadedFiles.value = aa //附件上传
					const result = fjcodelist.value.map(itemA => {
						const matchedItem = aa.find(itemB => itemB.remark === itemA.definitionName)
						//	console.log(matchedItem, 'matchedItem')
						if (matchedItem) {
							return { ...itemA, uploadedFiles: [matchedItem] } // 合并相同字段的数据
						}
						return itemA
					})
					fjcodelist.value = result //result赋值给 fjcodelist
				}
			})
		})
	},
	{ immediate: true }
)
const getedit = computed(() => {
	if (userStore.user.roleCode.includes('SB')) {
		if (Number(props.datainfo.progressStage) == 9) {
			if (props.datainfo.edit == 'true' && (Number(props.requestParams.progressStatus) < 10 || Number(props.requestParams.progressStatus) == 24)) {
				return true
			} else {
				return false
			}
		} else {
			return false
		}
	} else {
		return false
	}
})

const shangbaoshow = computed(() => {
	if (userStore.user.roleCode.includes('ZZADMIN') || userStore.user.roleCode.includes('SHZZ') || userStore.user.roleCode.includes('SYADMIN')) {
		if (Number(props.requestParams.progressStatus) == 10 && props.datainfo.edit == 'true') {
			return true
		} else {
			return false
		}
	} else {
		return false
	}
})

const zancunshow = computed(() => {
	if (userStore.user.roleCode.includes('SB')) {
		if (props.datainfo.edit == 'true') {
			if (Number(props.requestParams.progressStatus) == 9 || Number(props.requestParams.progressStatus) == 24) {
				return true
			} else {
				return false
			}
		} else {
			return false
		}
	} else {
		return false
	}
})
const validateBeforeSubmit = (requiredItems, uploadedFiles) => {
	const errors = []

	requiredItems.forEach(item => {
		const uploadedItem = uploadedFiles.some(file => file.remark === item.definitionName)
		if (!uploadedItem && item.imustUpload === 1) {
			errors.push(`【${item.definitionName}】未上传文件`)
		}
	})

	if (errors.length > 0) {
		ElMessage.error(errors.join(','))
		return false
	}

	return true
}

const rules = reactive({
	baopCompletionTime: [{ required: true, message: '请选择时间', trigger: 'change' }]
})

onMounted(() => {
	//	console.log(props.requestParams.solicitOpinionsBeforeFileList, '我是征求意见的附件')
	dictionaryStore.initCategory()
})

// 处理上传成功事件
const handleUploadSuccess = (data: any) => {
	uploadedFiles.value.push(data) // 将接口返回的数据添加到文件列表
}

// 处理文件删除事件
const handleFileRemove = (file: any) => {
	const id = file.response ? file.response.data.id : file.id
	uploadedFiles.value = uploadedFiles.value.filter(
		item => item.id !== id // 根据 uid 删除对应文件
	)
}

const cancelSubmit = (type: string, code: any) => {
	ElMessageBox.confirm('是否确认退回', '确认退回', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const data = {
				progressCode: 'ApprovalApplication',
				id: props.requestParams.id,
				progressStatus: 24
			}
			doReturnApi(data).then(res => {
				emit('updateData', '')
				ElMessage.success('退回成功')
				// nextTick(() => {
				// 	router.push({
				// 		path: '/bianzhi/shenbao/index'
				// 	})
				// })
			})
		})
		.catch(() => {})
}

const baoSubmit = (num: any) => {
	formParams.value.standardNumber = num ? num : props.requestParams.standardNumber
	//	props.requestParams.standardNumber = num ? num : props.requestParams.standardNumber
	if (!validateBeforeSubmit(fjcodelist.value, uploadedFiles.value)) {
		return
	}
	ElMessageBox.confirm('是否确认上报', '确认提交', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			Emittion('ReleaseImplementation', 11)
		})
		.catch(() => {})
}
const endSubmit = () => {
	if (!validateBeforeSubmit(fjcodelist.value, uploadedFiles.value)) {
		return
	}
	queryForm.value.validate(valid => {
		if (valid) {
			ElMessageBox.confirm('是否确认提交', '确认提交', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					Emittion('ApprovalApplication', 10)
				})
				.catch(() => {})
		} else {
			console.log('error submit!!')
			return false
		}
	})
}
const Emittion = (type: string, code: number) => {
	if (uploadedFiles.value.length > 0) {
		uploadedFiles.value.forEach(item => {
			delete item.name
		})
	}
	const filelist = [...uploadedFiles.value]

	const data = {
		expertsList: [],
		id: props.requestParams.id,
		standardProjectName: props.requestParams.name,
		standardNumber: props.requestParams.standardNumber,
		dgbzReviewTime: props.requestParams.dgbzReviewTime, //大纲评审时间  //大纲评审时间
		zqyjReviewTime: props.requestParams.zqyjReviewTime, //征求意见评审时间
		songsReviewTime: props.requestParams.songsReviewTime, //送审评审时间
		baopCompletionTime: formParams.value.baopCompletionTime, //报批时间
		// scopeApplication: formParams.value.scopeApplication, //适用范围
		releaseTime: props.requestParams.releaseTime, //发布时间
		implementationTime: props.requestParams.implementationTime, //实施时间
		progressCode: type,
		progressStatus: code,
		routeName: '/progressInfo',
		filesRecordList: filelist, //所有附件
		mainUnitList: [], //主编单位
		partUnitList: [], //参编单位
		projectMainDrafterList: [] //主要起草人员
	}

	updateStageAndStatusApi(data).then(res => {
		emit('updateData', '')
		ElMessage.success('提交成功')
		if (code == 11) {
			// nextTick(() => {
			// 	router.push({
			// 		path: '/bianzhi/shenbao/index'
			// 	})
			// })
		}
	})
}

const zanchSubmit = () => {
	if (uploadedFiles.value.length > 0) {
		uploadedFiles.value.forEach(item => {
			delete item.name
		})
	}
	const filelist = [...uploadedFiles.value]

	const data = {
		expertsList: [],
		id: props.requestParams.id,
		standardProjectName: props.requestParams.name,
		standardNumber: props.requestParams.standardNumber,
		dgbzReviewTime: props.requestParams.dgbzReviewTime, //大纲评审时间  //大纲评审时间
		zqyjReviewTime: props.requestParams.zqyjReviewTime, //征求意见评审时间
		songsReviewTime: props.requestParams.songsReviewTime, //送审评审时间
		baopCompletionTime: props.requestParams.baopCompletionTime, //报批时间
		// scopeApplication: formParams.value.scopeApplication, //适用范围
		releaseTime: props.requestParams.releaseTime, //发布时间
		implementationTime: props.requestParams.implementationTime, //实施时间
		progressCode: 'ApprovalApplication',
		routeName: '/progressInfo',
		filesRecordList: filelist, //所有附件
		mainUnitList: [], //主编单位
		partUnitList: [], //参编单位
		projectMainDrafterList: [] //主要起草人员
	}

	updateProgressApi(data).then(res => {
		emit('updateData', '')
		ElMessage.success('暂存成功')
		// nextTick(() => {
		// 	router.push({
		// 		path: '/bianzhi/shenbao/index'
		// 	})
		// })
	})
}
const route = useRoute()

// 标准信息查看
const handleBiaozhun = () => {
	showAddDialog.value = true
	// console.log(props.datainfo)
	editId.value = ''
	projectId.value = route.query.pid.toString()
}

// 报批资料下载
const handleFileDownload = () => {
	const id = props.datainfo.id
	if (!id) {
		ElMessage.warning('标准ID不存在，无法下载报批资料')
		return
	}

	ElMessageBox.confirm('是否确认下载报批资料', '下载报批资料', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const baseURL = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/`
			// /api/preparationProgress/exportApprovalList
			axios({
				method: 'post',
				url: baseURL + '/api/preparationProgress/exportApprovalList',
				headers: {
					'Content-Type': 'application/json;charset=UTF-8',
					Authorization: userStore.token
				},
				data: { id: id },
				responseType: 'blob'
			})
				.then(response => {
					const type = response.headers['content-type']
					const filename = response.headers['content-disposition']
						? decodeURIComponent(response.headers['content-disposition'].split('filename=')[1])
						: '报批资料.docx'
					const blob = new Blob([response.data], { type: type })
					const blobHref = URL.createObjectURL(blob)
					if ('download' in document.createElement('a')) {
						// 非IE下载
						const elink = document.createElement('a')
						elink.download = filename
						elink.style.display = 'none'
						elink.href = blobHref
						document.body.appendChild(elink)
						elink.click()
						URL.revokeObjectURL(blobHref) // 释放URL 对象
						document.body.removeChild(elink)
					} else {
						ElMessage.error('当前浏览器不支持下载功能，请更换浏览器后重试！')
					}
				})
				.catch(error => {
					ElMessage.error('下载失败')
				})
		})
		.catch(() => {})
}
</script>

<style lang="scss" scoped>
.card-header-box1 {
	display: flex;

	flex-direction: column;

	overflow-y: scroll;
	height: 100%;

	&::-webkit-scrollbar {
		display: none;
	}

	.titlezi {
		font-size: 16px;
		color: #333;
	}

	.kuaibj {
		background-color: #f5f6fa;
		padding: 20px;
		border-radius: 6px;
	}

	.fjsmzi {
		font-size: 12px;
		color: #606266;
		margin-left: 5px;
	}
}
</style>
